<?php
class Account extends Admin_Controller
{
	
	function __construct()
	{
		parent::__construct();
		$this->load->model('voucher/fund_model','fund');
		$this->load->model('account_model','account');
	}
	
	function index($fund_id)
	{
		$data['fund'] = $this->fund->get_row($fund_id);
		$where = '';
		if(!empty($_GET['search']))
		{
			$where .= ' and accounts.name like \'%'.$_GET['search'].'%\'';
		}
		if(!empty($_GET['category_id']))
		{
			$where .= ' and accounts.category_id = '.$_GET['category_id'];
		}
		$data['result'] = $this->account->where('fund_id = '.$fund_id.$where)->sort('code')->order('asc')->limit(100)->get();
		$data['pagination'] = $this->account->pagination();
		$this->template->build('account_index',$data);
	}
	
	function form($fund_id,$id = NULL)
	{
		$data['fund'] = $this->fund->get_row($fund_id);
		$data['rs'] = $this->account->get_row($id);
		$this->template->append_metadata(js_validate());
		$this->template->build('account_form',$data);
	}
	
	function save()
	{
		if($_POST)
		{
			if(empty($_POST['id']))
			{
				add_log('เพิ่มชื่อบัญชี "'.$_POST['name'].'"');
			}
			else
			{
				add_log('แก้ไขชื่อบัญชี "'.$_POST['name'].'"');
			}
			if(empty($_POST['money']))
			{
				$_POST['money'] = '';
			}
			else
			{
				$this->db->execute('update accounts set group_id = NULL,money = NULL where fund_id = '.$_POST['fund_id'].' and money = '.$_POST['money']);
			}
			$this->account->save($_POST);
			set_notify('success', lang('save_data_complete'));
		}
		redirect('account/index/'.$_POST['fund_id']);
	}
	
	function delete($id)
	{
		$rs = $this->account->get_row($id);
		add_log('ลบชื่อบัญชี "'.$rs['name'].'"');
		$this->account->delete($id);
		set_notify('success', lang('delete_data_complete'));
		redirect($_SERVER['HTTP_REFERER']);
	}
	
	function ddl($fund_id)
	{
		echo form_dropdown('account_id',get_option('ID','NAME','ACCOUNTS',' FUND_ID = '.$fund_id));
	}
	
	function check_account($fund_id)
	{
		$flag = $this->db->getOne('select id from accounts where fund_id = ? and name = ?',array($fund_id,iconv('UTF-8','TIS-620',$_GET['name'])));	
		echo ($flag)?"false":"true";
	}

}
?>